package com.example.demo.controller;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.controller.dto.admin.LoginDto;
import com.example.demo.util.JWTUtil;
import com.example.demo.util.R;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/admin")
@Api(value = "管理员登录", tags = { "管理员接口" })
public class AdminController {

  private String name = "admin";
  private String password = "123456";

  @PostMapping("/login")
  @ApiOperation(value = "登录")
  public R login(@RequestBody LoginDto loginDto) {

    if (!loginDto.getName().equals(this.name) || !loginDto.getPassword().equals(this.password)) {
      return R.fail("用户名或密码错误");
    }

    String token = JWTUtil.getToken(loginDto.getName(), loginDto.getPassword());

    return R.success("登录成功", token);
  }

  @PostMapping("/verify")
  @ApiOperation(value = "验证token")
  public R verify(
      HttpServletRequest request) {

    String token = request.getHeader("token");

    boolean valid = JWTUtil.verify(token);

    if (!valid) {
      return R.fail("验证失败");
    }

    DecodedJWT claim = JWTUtil.getClaim(token);

    HashMap<String, String> map = new HashMap<String, String>();

    map.put("getAlgorithm", claim.getAlgorithm());
    map.put("name", claim.getClaim("name").asString());
    map.put("password", claim.getClaim("password").asString());
    map.put("valid", valid + "");

    return R.success("验证成功", map);
  }

  @PostMapping("/logout")
  @ApiOperation(value = "登出")
  public R logout(
      HttpServletRequest request) {

    return R.success("退出成功");
  }

}
